package sample9;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;

public class GridLayoutDemo extends JFrame {

	public GridLayoutDemo(String name) {
		super(name);
		setResizable(false);
	}

	public static void main(String[] args) {

		final String gapList[] = { "0", "10", "15", "20" };
		final int maxGap = 20;
		final JComboBox horGapComboBox;
		final JComboBox verGapComboBox;
		JButton applyButton = new JButton("Apply gaps");
		final GridLayout experimentLayout = new GridLayout(0, 2);

		GridLayoutDemo frame = new GridLayoutDemo("GridLayoutDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		horGapComboBox = new JComboBox(gapList);
		verGapComboBox = new JComboBox(gapList);

		final JPanel compsToExperiment = new JPanel();
		compsToExperiment.setLayout(experimentLayout);
		JPanel controls = new JPanel();
		controls.setLayout(new GridLayout(2, 3));

		JButton b = new JButton("Just fake button");
		Dimension buttonSize = b.getPreferredSize();
		compsToExperiment.setPreferredSize(new Dimension((int) (buttonSize.getWidth() * 2.5) + maxGap,
				(int) (buttonSize.getHeight() * 3.5) + maxGap * 2));

		// Add buttons to experiment with Grid Layout
		compsToExperiment.add(new JButton("Button 1"));
		compsToExperiment.add(new JButton("Button 2"));
		compsToExperiment.add(new JButton("Button 3"));
		compsToExperiment.add(new JButton("Long-Named Button 4"));
		compsToExperiment.add(new JButton("5"));

		// Add controls to set up horizontal and vertical gaps
		controls.add(new Label("Horizontal gap:"));
		controls.add(new Label("Vertical gap:"));
		controls.add(new Label(" "));
		controls.add(horGapComboBox);
		controls.add(verGapComboBox);
		controls.add(applyButton);

		// Process the Apply gaps button press
		applyButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// Get the horizontal gap value
				String horGap = (String) horGapComboBox.getSelectedItem();
				// Get the vertical gap value
				String verGap = (String) verGapComboBox.getSelectedItem();
				// Set up the horizontal gap value
				experimentLayout.setHgap(Integer.parseInt(horGap));
				// Set up the vertical gap value
				experimentLayout.setVgap(Integer.parseInt(verGap));
				// Set up the layout of the buttons
				experimentLayout.layoutContainer(compsToExperiment);
			}
		});
		frame.add(compsToExperiment, BorderLayout.NORTH);
		frame.add(new JSeparator(), BorderLayout.CENTER);
		frame.add(controls, BorderLayout.SOUTH);

		frame.setSize(800, 600);
		frame.setVisible(true);

	}
}